from django.shortcuts import render
from common import utils
from django.http import HttpResponse
from .models import Note,File
import json
import csv
from django.core.paginator import Paginator
from django.contrib.auth.models import User as DjangoUser
from django.contrib.auth import authenticate, login,logout
from django.contrib.auth.decorators import login_required
import hashlib
# Create your views here.
from django.views.decorators.cache import cache_page
from django.conf import settings
# Create your views here.
@utils.check_login
def note_add(request):
    if request.method=='GET':
        return render(request,'notes/note_add.html')
    elif request.method == 'POST':
        try:
            req_data = json.loads(request.body)
            title = req_data.get('title')
            content = req_data.get('content')
            uid = request.user_id
            note = Note.objects.create(title=title, content=content,user_id=uid)
            data = {
                'note':note.title
            }
            return utils.Response(data=data)
        except Exception as e:
            return utils.Response(result=0, msg=str(e))


@utils.check_login
def note_list(request):
    try:
        page_number = int(request.GET.get('page',1))
        uid = request.user_id
        note = Note.objects.filter(user_id=uid,status__in=[1,-1])
        # 每页显示10条数据
        p = Paginator(note, 5)
        count = p.count
        # 获取第几页的数据
        page_obj = p.get_page(page_number)
        return render(request, 'notes/note_show.html', {'page_obj': page_obj})
    except Exception as e:
        return HttpResponse(str(e))

@utils.check_login
def note_detail(request,id):
    try:
        uid = request.user_id
        note_obj = Note.objects.filter(id=id,status=1).first()
        if note_obj and (note_obj.user_id == uid or note_obj.is_pub == 0):
            return render(request, 'notes/note_detail.html', {'note_obj': note_obj})
        return render(request,'error/forbid.html',{"forbid_tip":"文章不存在或未公开"})
    except Exception as e:
        return HttpResponse(str(e))

@login_required
def note_csv(request):
    resp = HttpResponse(content_type='text/csv')
    resp['Content-Disposition'] = 'attachment;filename="test.csv"'
    note = Note.objects.all().values_list('title',flat=True)
    writer = csv.writer(resp)
    writer.writerows(note)
    return resp

# def django_user(request):
#     # 创建普通用户和超管用户
#     # user = DjangoUser.objects.create_user(username='用户名1',password='qishi#09319',email='1287933507@qq.com')
#     # user = DjangoUser.objects.create_superuser(username='用户名admin',password='qishi#09319',email='1287933507@qq.com')
#     # 密码校验，成功返回对象，失败返回None
#     user = authenticate(username='用户名admin',password='zywx@2021')
#     # 密码修改
#     # user = DjangoUser.objects.get(username='用户名admin')
#     # user.set_password('zywx@2021')
#     # user = user.save()
#     login(request,user)
#     return HttpResponse(user)
    
import os
def test_upload(request):
    if request.method== 'GET':
        return render(request,'notes/test_upload.html')
    elif request.method == "POST":
        print(request.FILES)
        file= request.FILES['myfile']
        md5 = hashlib.md5()
        filename = file.name.split('.')
        md5.update(filename[0].encode('utf8'))
        filename = md5.hexdigest()+'.'+filename[1]
        if file.size >= 1024*1024*1024:
            return HttpResponse("文件太大了"+str(file.size))
        # filename = os.path.join(settings.MEDIA_ROOT, filename)
        # filesize = file.size
        print(filename)
        f = File.objects.create(filename=filename[:5],file=file)
        
        # with open(filename,'wb') as f:
        #     f.write(file.file.read())
        return HttpResponse(f.filename+str(f.file))


